package com.example.onlinemonitoring.comCenter;

import com.example.onlinemonitoring.Util.CRC16;
import com.example.onlinemonitoring.Util.CommPortManager;
import com.example.onlinemonitoring.dao.DlqjchistoryTestMapper;
import com.example.onlinemonitoring.dao.DlqjcsensorTestMapper;
import com.example.onlinemonitoring.model.Appdevice;
import com.example.onlinemonitoring.model.Dlqjchistory;
import com.example.onlinemonitoring.model.DlqjchistoryTest;
import com.example.onlinemonitoring.model.Dlqjcsensor;
import com.example.onlinemonitoring.model.DlqjcsensorTest;
import com.example.onlinemonitoring.serviceImpl.DlqjcsensorServiceImpl;

import lombok.Data;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.context.annotation.Scope;
import tk.mybatis.mapper.entity.Example;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 断路器
 */
@Service("dlqjcCom")
@Scope("prototype")
@Data
public class DlqjcCom extends CommPortManager {
    @Value("${DlqConfig.expirationTime}")
    Long expirationTime;
    Map<String, String> strmap = new HashMap<>();
    String statusdisplay[] = { "未知", "合闸", "主分", "副分", "储能" };
    String strdisplay[] = { "A相电闸状态:", "B相电闸状态:", "C相电闸状态:" };
    String strstatus[] = { "断路器A相:", "断路器B相:", "断路器C相:" };
    String stralarm[] = { "铁芯卡涩,", "铁芯卡滞,", "电压偏离,", "铁芯总行程及空行程均太小," };
    @Autowired
    private DlqjcsensorServiceImpl dlqserviceimpl;
    @Autowired
    private DlqjcsensorTestMapper dlqjcsensortestmapper;
    @Autowired
    private DlqjchistoryTestMapper dlqjchistorytestmapper;
    private boolean tripopen = false;
    // 锁对象
    public Object lock = new Object();
    int[] lastmstate = new int[7000];// 记录上次是什么动作
    boolean[] isfenhe = new boolean[7000];// 是否有动作
    int[] tripcount = new int[7000];// 行程计数

    @Override
    public void receiveData(String str) {
        try {
            synchronized (lock) {
                str = str.toUpperCase();
                String addrstr = str.substring(2, 4);
                Integer addrint = parseHex4(addrstr) + 6010;
                reSend[parseHex4(addrstr)] = 0;
                addrindex++;

                switch (str.substring(4, 6)) {
                    case "F0": {// 分合闸动作数据
                        setText("分合闸动作数据已收到！");
                        receiveData2(str, addrint);
                    }
                        ;
                        break;
                    case "F1": {// 行程数据
                        setText("行程数据已收到！");
                        receiveData1(str, addrint);
                    }
                        ;
                        break;
                    case "F2": {// 常态电流数据
                        setText("常态电流数据已收到！");
                        receiveDataNormal(str, addrint);
                    }
                        ;
                        break;
                    case "F3": {// 写入参数的控制返回
                        controllerRet = str;
                    }
                        ;
                        break;
                }
                Thread.sleep((int) Math.round(ad.getTimersp() * 1000));
                lock.notifyAll();
            }
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }

    // 无曲线，普通电流
    private void receiveDataNormal(String str, Integer addrint) {
        Dlqjcsensor dlq = new Dlqjcsensor();
        dlq.setStationid(ad.getStationid());
        dlq.setDevicegroup(ad.getDevicegroup());
        dlq.setDeviceaddr(addrint);
        dlq.setCmd(67);
        Example example = new Example(Dlqjcsensor.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("stationid", dlq.getStationid());
        criteria.andEqualTo("deviceaddr", dlq.getDeviceaddr());
        criteria.andEqualTo("devicegroup", dlq.getDevicegroup());
        criteria.andEqualTo("cmd", dlq.getCmd());
        dlq = dlqserviceimpl.selectOneByExample(example);
        if (dlq == null) {
            setText("当前数据库无监测点：" + addrint + " ！ 请先添加该监测点！");
            return;
        }
        float ratio = dlq.getRatioconfig();
        String abcstatus = str.substring(8, 20);
        String acurrentstr = abcstatus.substring(0, 4);
        String bcurrentstr = abcstatus.substring(4, 8);
        String ccurrentstr = abcstatus.substring(8, 12);

        String abccur = str.substring(20, 38);
        Integer ast = parseHex4(abccur.substring(0, 2));
        Integer bst = parseHex4(abccur.substring(2, 4));
        Integer cst = parseHex4(abccur.substring(4, 6));
        Float acur = parseHex4(abccur.substring(6, 10)) * ratio / 100f;
        Float bcur = parseHex4(abccur.substring(10, 14)) * ratio / 100f;
        Float ccur = parseHex4(abccur.substring(14, 18)) * ratio / 100f;

        String abcstatus2 = str.substring(38, 50);
        Integer LastAState = parseHex4(abcstatus2.substring(0, 2));
        Integer LastAStorageState = parseHex4(abcstatus2.substring(2, 4));
        Integer LastBState = parseHex4(abcstatus2.substring(4, 6));
        Integer LastBStorageState = parseHex4(abcstatus2.substring(6, 8));
        Integer LastCState = parseHex4(abcstatus2.substring(8, 10));
        Integer LastCStorageState = parseHex4(abcstatus2.substring(10, 12));

        // if (LastAState == 0 || LastBState == 0 || LastCState == 0) {
        // return;
        // }

        float acurrent = parseHex4(acurrentstr) * ratio / 100f;
        float bcurrent = parseHex4(bcurrentstr) * ratio / 100f;
        float ccurrent = parseHex4(ccurrentstr) * ratio / 100f;
        String statusdisplay[] = { "未知", "合闸", "分闸" };
        String statushavechanged[] = { "没有改变", "已改变" };

        setText("A改变前电流：" + acurrent + "A " + statusdisplay[LastAState] +
                " B改变前电流：" + bcurrent + "B " + statusdisplay[LastBState] +
                " C改变前电流：" + ccurrent + "C " + statusdisplay[LastCState]);
        setText("A改变后电流：" + acur + "A " + statushavechanged[ast] +
                " B改变后电流：" + bcur + "B " + statushavechanged[bst] +
                " C改变后电流：" + ccur + "C " + statushavechanged[cst]);
        dlq.setLaststate(-1);
        dlq.setLastaacurrent(acur);
        dlq.setLastbacurrent(bcur);
        dlq.setLastcacurrent(ccur);
        dlq.setLastaastatus(ast);
        dlq.setLastbastatus(bst);
        dlq.setLastcastatus(cst);
        dlq.setLastastate(LastAState);
        dlq.setLastastoragestate(LastAStorageState);
        dlq.setLastbstate(LastBState);
        dlq.setLastbstoragestate(LastBStorageState);
        dlq.setLastcstate(LastCState);
        dlq.setLastcstoragestate(LastCStorageState);
        dlq.setLastaccurrent(acurrent);
        dlq.setLastbccurrent(bcurrent);
        dlq.setLastcccurrent(ccurrent);
        dlq.setLastcommunicationstatus(0);
        dlq.setLastdatatime(new Date());
        if (dlqserviceimpl.updateByPrimaryKeySelective(dlq) == 0) {
            setText("数据更新失败！请检查原因...");
        }
        dlqserviceimpl.UpdateStatus(ad, dlq.getDeviceaddr(), 0);
        // addhis(dlq);
    }

    // 有行程曲线,2022825新增
    private void receiveData1(String str, Integer addrint) {
        isfenhe[addrint] = false;
        tripcount[addrint] = 0;
        String abcstatus = str.substring(6, 102);
        String astr = abcstatus.substring(0, 32);
        String bstr = abcstatus.substring(32, 64);
        String cstr = abcstatus.substring(64, 96);
        List<String> qstr = new LinkedList<>();
        qstr.add(astr);
        qstr.add(bstr);
        qstr.add(cstr);
        for (int n = 0; n < 3; n++) {
            SensorData2(qstr.get(n), addrint, n);
        }
    }

    // 有电流曲线
    private void receiveData2(String str, Integer addrint) {
        Dlqjcsensor dlq = new Dlqjcsensor();
        dlq.setStationid(ad.getStationid());
        dlq.setDevicegroup(ad.getDevicegroup());
        dlq.setDeviceaddr(addrint);
        dlq.setCmd(67);
        Example example = new Example(Dlqjcsensor.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("stationid", dlq.getStationid());
        criteria.andEqualTo("deviceaddr", dlq.getDeviceaddr());
        criteria.andEqualTo("devicegroup", dlq.getDevicegroup());
        criteria.andEqualTo("cmd", dlq.getCmd());
        dlq = dlqserviceimpl.selectOneByExample(example);
        if (dlq == null) {
            setText("当前数据库无监测点：" + addrint + " ！ 请先添加该监测点！");
            return;
        }
        String astr = str.substring(6, 154);
        String bstr = str.substring(154, 302);
        String cstr = str.substring(302, 450);
        List<String> qstr = new LinkedList<>();
        qstr.add(astr);
        qstr.add(bstr);
        qstr.add(cstr);
        // 老版本勿删
        // if (ad.getSubswitch().equals("0")) {
        // String abcstatus = str.substring(450, 480);
        // String acurrentstr = abcstatus.substring(2, 6);
        // String bcurrentstr = abcstatus.substring(6, 10);
        // String ccurrentstr = abcstatus.substring(10, 14);

        // Integer LastAState = parseHex4(abcstatus.substring(14, 16));
        // Integer LastBState = parseHex4(abcstatus.substring(18, 20));
        // Integer LastCState = parseHex4(abcstatus.substring(22, 24));
        // Integer LastAStorageState = parseHex4(abcstatus.substring(16, 18));
        // Integer LastBStorageState = parseHex4(abcstatus.substring(20, 22));
        // Integer LastCStorageState = parseHex4(abcstatus.substring(24, 26));

        // float ratio = dlq.getRatioconfig();
        // float acurrent = parseHex4(acurrentstr) * ratio / 100f;
        // float bcurrent = parseHex4(bcurrentstr) * ratio / 100f;
        // float ccurrent = parseHex4(ccurrentstr) * ratio / 100f;
        // String statusdisplay[] = { "未知", "合闸", "分闸" };
        // String storagedisplay[] = { "未知", "储能", "未储能" };

        // // 2021.8.30后新增
        // if (str.length() == 496) {
        // String abccur = str.substring(476, 496);
        // Float acur = parseHex4(abccur.substring(0, 4)) * ratio / 100f;
        // Float bcur = parseHex4(abccur.substring(4, 8)) * ratio / 100f;
        // Float ccur = parseHex4(abccur.substring(8, 12)) * ratio / 100f;
        // Integer ast = parseHex4(abccur.substring(12, 14));
        // Integer bst = parseHex4(abccur.substring(14, 16));
        // Integer cst = parseHex4(abccur.substring(16, 18));
        // dlq.setLastaacurrent(acur);
        // dlq.setLastbacurrent(bcur);
        // dlq.setLastcacurrent(ccur);
        // dlq.setLastaastatus(ast);
        // dlq.setLastbastatus(bst);
        // dlq.setLastcastatus(cst);
        // }
        // dlq.setLaststate(-1);
        // dlq.setLastastate(LastAState);
        // dlq.setLastastoragestate(LastAStorageState);
        // dlq.setLastbstate(LastBState);
        // dlq.setLastbstoragestate(LastBStorageState);
        // dlq.setLastcstate(LastCState);
        // dlq.setLastcstoragestate(LastCStorageState);
        // dlq.setLastaccurrent(acurrent);
        // dlq.setLastbccurrent(bcurrent);
        // dlq.setLastcccurrent(ccurrent);
        // SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
        // dlq.setLastalarmlevel(0);
        // dlq.setLastalarmmessage("");
        // }

        if (dlq.getLastaccurrent() == 0 && dlq.getLastbccurrent() == 0 && dlq.getLastcccurrent() == 0) {
            if ((dlq.getLastaastatus() != 0 || dlq.getLastbastatus() != 0 || dlq.getLastcastatus() != 0)) {
                int at = parseHex4(str.substring(76, 78));
                int bt = parseHex4(str.substring(224, 226));
                int ct = parseHex4(str.substring(372, 374));
                if (Math.abs(at - bt) > 5 || Math.abs(at - ct) > 5 || Math.abs(ct - bt) > 5) {
                    dlq.setLastalarmlevel(1);
                    dlq.setLastalarmmessage("三相不同期预警！");
                }
            }
        }
        dlq.setLastdatatime(new Date());
        dlq.setLastcommunicationstatus(0);
        if (dlqserviceimpl.updateByPrimaryKeySelective(dlq) == 0) {
            setText("数据更新失败！请检查原因...");
        }
        isfenhe[addrint] = true;
        for (int n = 0; n < 3; n++) {
            SensorData(qstr.get(n), addrint, dlq);
        }
    }

    void SensorData(String data, Integer addrint, Dlqjcsensor temp) {
        Integer LastState, cmd;
        cmd = parseHex4(data.substring(0, 2));
        LastState = parseHex4(data.substring(2, 4));
        if (LastState == 0)
            return;
        String astr = data.substring(4, 40);
        String bstr = data.substring(40, 76);
        String cstr = data.substring(76, 112);
        String dstr = data.substring(112, 148);
        List<String> qstr = new LinkedList<>();

        qstr.add(astr);
        qstr.add(bstr);
        qstr.add(cstr);
        qstr.add(dstr);
        if ((LastState & 0x01) == 0x01) {// 合闸
            SensorData(qstr.get(0), addrint, 1, cmd, temp);
            if (tripopen) {
                lastmstate[addrint] = 1;
            }
        }
        if ((LastState & 0x02) == 0x02) {// 主分
            SensorData(qstr.get(1), addrint, 2, cmd, temp);
            if (tripopen) {
                lastmstate[addrint] = 2;
            }
        }
        if ((LastState & 0x04) == 0x04) {// 副分
            SensorData(qstr.get(2), addrint, 3, cmd, temp);
        }
        if ((LastState & 0x08) == 0x08) {// 储能
            SensorData(qstr.get(3), addrint, 4, cmd, temp);
        }
    }

    void SensorData2(String data, Integer addrint, int index) {
        Dlqjcsensor dlqm = new Dlqjcsensor();
        dlqm.setStationid(ad.getStationid());
        dlqm.setDevicegroup(ad.getDevicegroup());
        dlqm.setDeviceaddr(addrint);
        dlqm.setCmd(67);
        dlqm = dlqserviceimpl.getModel(dlqm);
        if (dlqm == null) {
            setText("当前数据库无监测点：" + addrint + " ！ 请先添加该监测点！");
            return;
        }
        if (data.substring(2, 4).equals("01")) {
            int laststate = 0;
            laststate = lastmstate[addrint];
            if (laststate == 0) {
                return;
            }
            Example example = new Example(Dlqjcsensor.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("stationid", ad.getStationid());
            criteria.andEqualTo("deviceaddr", ad.getDeviceaddr());
            criteria.andEqualTo("devicegroup", ad.getDevicegroup());
            criteria.andEqualTo("cmd", index + 64);
            criteria.andEqualTo("laststate", laststate);
            List<Dlqjcsensor> dlq = dlqserviceimpl.selectByExample(example);
            if (dlq.size() == 0) {
                setText("当前数据库无监测点：" + addrint + " ！ 请先添加该监测点！");
                return;
            }
            Integer st0 = 0;
            Integer s0 = 0;
            Integer st1 = dlq.get(0).getLastt1time();
            Integer s1 = parseHex4(data.substring(8, 12)) / 10;
            Integer st2 = Math.round(Integer.parseInt(data.substring(4, 8), 16) / 75f);
            Integer s2 = parseHex4(data.substring(8, 12));
            Integer st3 = Math.round(Integer.parseInt(data.substring(12, 16), 16) / 75f);
            Integer s3 = parseHex4(data.substring(16, 20));
            Integer st4 = Math.round(Integer.parseInt(data.substring(20, 24), 16) / 75f);
            Integer s4 = parseHex4(data.substring(24, 28));
            Float lastspeed = Integer.parseInt(data.substring(28, 32), 16) / 100f;
            Dlqjcsensor dlqu = new Dlqjcsensor();
            Integer y0, y1, y2, y3, y4;
            if (dlq.get(0).getFirsts2() == null || dlq.get(0).getFirsts2() == 0) {// 第一次
                y4 = s4;
                y3 = s3;
                y2 = s2;
                y1 = s1;
                y0 = s0;
                dlqu.setFirsts2(y4);
            } else {
                y4 = s4 / dlq.get(0).getFirsts2() * (dlq.get(0).getTrip() + dlq.get(0).getOd());
                y3 = y4 / 3 * 2;
                y2 = y4 / 3;
                y1 = s1;
                y0 = 0;
            }
            float[][] point = { { st0, y0 }, { st1, y1 }, { st2, y2 }, { st3, y3 }, { st4, y4 } };
            float[][] res = bezier(point, 20);
            String s = "", t = "";
            for (int i = 0; i < res.length; i++) {
                s += res[i][0] + ",";
                t += res[i][1] + ",";
            }

            dlqu.setPointname(dlq.get(0).getPointname());
            dlqu.setStationid(ad.getStationid());
            dlqu.setDevicegroup(ad.getDevicegroup());
            dlqu.setDeviceaddr(addrint);
            dlqu.setCmd(index + 64);
            dlqu.setLaststate(laststate);

            dlqu.setLastst0time(st0);
            dlqu.setLastst1time(st1);
            dlqu.setLastst2time(st2);
            dlqu.setLastst3time(st3);
            dlqu.setLastst4time(st4);
            dlqu.setLastst5time(st4 + 10);
            dlqu.setLasts0((int) y0);
            dlqu.setLasts1((int) y1);
            dlqu.setLasts2((int) y2);
            dlqu.setLasts3((int) y3);
            dlqu.setLasts4((int) y4);
            dlqu.setLasts5((int) y4);
            dlqu.setLastspeed(lastspeed);
            Example example1 = new Example(Dlqjcsensor.class);
            Example.Criteria criteria1 = example1.createCriteria();
            criteria1.andEqualTo("stationid", dlqu.getStationid());
            criteria1.andEqualTo("deviceaddr", dlqu.getDeviceaddr());
            criteria1.andEqualTo("devicegroup", dlqu.getDevicegroup());
            criteria1.andEqualTo("cmd", dlqu.getCmd());
            criteria1.andEqualTo("laststate", dlqu.getLaststate());
            // 2023.12.9新增
            if (dlqu.getLasts0() == 0 && dlqu.getLasts1() == 0 && dlqu.getLasts2() == 0 && dlqu.getLasts3() == 0
                    && dlqu.getLasts4() == 0 && dlqu.getLasts5() == 0) {
                return;
            }
            //
            if (dlqserviceimpl.updateByExampleSelective(dlqu, example1) == 0) {
                setText("数据更新失败！请检查原因...");
            }

            dlqu.setLastt0time(st0);
            dlqu.setLastt1time(st1);
            dlqu.setLastt2time(st2);
            dlqu.setLastt3time(st3);
            dlqu.setLastt4time(st4);
            dlqu.setLastt5time(st4 + 10);
            dlqu.setLasti0current((float) y0);
            dlqu.setLasti1current((float) y1);
            dlqu.setLasti2current((float) y2);
            dlqu.setLasti3current((float) y3);
            dlqu.setLasti4current((float) y4);
            dlqu.setLasti5current((float) y4);
            addtest(dlqu);
            switch (index) {
                case 0:
                    setText("A相行程曲线已分析完毕");
                    break;
                case 1:
                    setText("B相行程曲线已分析完毕");
                    break;
                case 2:
                    setText("C相行程曲线已分析完毕");
                    break;

                default:
                    break;
            }
        }
    }

    void SensorData(String data, Integer addrint, Integer LastState, Integer cmd, Dlqjcsensor temp) {

        Integer LastT0Time, LastT1Time, LastT2Time, LastT3Time, LastT4Time, LastT5Time;
        Float LastI0Current, LastI1Current, LastI2Current, LastI3Current, LastI4Current, LastI5Current;
        if (LastState != 4) {
            LastT0Time = parseHex4(data.substring(0, 2));
            LastT1Time = parseHex4(data.substring(6, 8));
            LastT2Time = parseHex4(data.substring(12, 14));
            LastT3Time = parseHex4(data.substring(18, 20));
            LastT4Time = parseHex4(data.substring(24, 26));
            LastT5Time = parseHex4(data.substring(30, 32));
        } else {
            LastT0Time = parseHex4(data.substring(0, 2)) / 100;
            LastT1Time = parseHex4(data.substring(6, 8)) / 10;
            LastT2Time = parseHex4(data.substring(12, 14)) / 10;
            LastT3Time = parseHex4(data.substring(18, 20)) / 10;
            LastT4Time = parseHex4(data.substring(24, 26)) / 10;
            LastT5Time = parseHex4(data.substring(30, 32)) / 10;
        }

        LastI0Current = parseHex4(data.substring(2, 6)) / 100f;
        LastI1Current = parseHex4(data.substring(8, 12)) / 100f;
        LastI2Current = parseHex4(data.substring(14, 18)) / 100f;
        LastI3Current = parseHex4(data.substring(20, 24)) / 100f;
        LastI4Current = parseHex4(data.substring(26, 30)) / 100f;
        LastI5Current = parseHex4(data.substring(32, 36)) / 100f;
        if (LastI1Current == 0 || LastI2Current == 0 || LastI3Current == 0) {// 2022922维持数据稳定
            Dlqjcsensor dlq = new Dlqjcsensor();
            dlq.setStationid(ad.getStationid());
            dlq.setDeviceaddr(addrint);
            dlq.setDevicegroup(ad.getDevicegroup());
            dlq.setLaststate(LastState);
            Example example = new Example(Dlqjcsensor.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("stationid", dlq.getStationid());
            criteria.andEqualTo("deviceaddr", dlq.getDeviceaddr());
            criteria.andEqualTo("devicegroup", dlq.getDevicegroup());
            criteria.andEqualTo("laststate", dlq.getLaststate());
            criteria.andNotEqualTo("lasti1current", 0);
            criteria.andNotEqualTo("lasti2current", 0);
            criteria.andNotEqualTo("lasti3current", 0);
            List<Dlqjcsensor> dlqlist = dlqserviceimpl.selectByExample(example);
            if (dlqlist.size() == 0) {
                LastI0Current = 0.58f;
                LastI1Current = 1.94f;
                LastI2Current = 1.48f;
                LastI3Current = 1.67f;
                LastI4Current = 1.77f;
                LastI5Current = 0f;
                LastT0Time = 0;
                LastT1Time = 3;
                LastT2Time = 10;
                LastT3Time = 11;
                LastT4Time = 12;
                LastT5Time = 18;
            } else {
                LastI0Current = dlqlist.get(0).getLasti0current();
                LastI1Current = dlqlist.get(0).getLasti1current();
                LastI2Current = dlqlist.get(0).getLasti2current();
                LastI3Current = dlqlist.get(0).getLasti3current();
                LastI4Current = dlqlist.get(0).getLasti4current();
                LastI5Current = dlqlist.get(0).getLasti5current();
                LastT0Time = dlqlist.get(0).getLastt0time();
                LastT1Time = dlqlist.get(0).getLastt1time();
                LastT2Time = dlqlist.get(0).getLastt2time();
                LastT3Time = dlqlist.get(0).getLastt3time();
                LastT4Time = dlqlist.get(0).getLastt4time();
                LastT5Time = dlqlist.get(0).getLastt5time();
            }
        }
        Dlqjcsensor dlq = new Dlqjcsensor();
        dlq.setStationid(ad.getStationid());
        dlq.setDeviceaddr(addrint);
        dlq.setDevicegroup(ad.getDevicegroup());
        dlq.setCmd(cmd);
        dlq.setLaststate(LastState);
        Example example = new Example(Dlqjcsensor.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("stationid", dlq.getStationid());
        criteria.andEqualTo("deviceaddr", dlq.getDeviceaddr());
        criteria.andEqualTo("devicegroup", dlq.getDevicegroup());
        criteria.andEqualTo("cmd", dlq.getCmd());
        criteria.andEqualTo("laststate", dlq.getLaststate());
        dlq = dlqserviceimpl.selectOneByExample(example);

        DlqjcsensorTest dlqtest = new DlqjcsensorTest();
        dlqtest.setDeviceaddr(addrint);
        dlqtest.setLaststate(LastState);
        example = new Example(DlqjcsensorTest.class);
        criteria = example.createCriteria();
        criteria.andEqualTo("stationid", dlq.getStationid());
        criteria.andEqualTo("deviceaddr", addrint);
        criteria.andEqualTo("devicegroup", dlq.getDevicegroup());
        criteria.andEqualTo("laststate", dlq.getLaststate());
        dlqtest = dlqjcsensortestmapper.selectOneByExample(example);
        if (dlqtest.getLastt0time() == 0 && dlqtest.getLastt1time() == 0 && dlqtest.getLastt2time() == 0
                && dlqtest.getLastt3time() == 0 && dlqtest.getLastt4time() == 0 && dlqtest.getLastt5time() == 0) {
            setText("断路器" + dlq.getDeviceaddr() + "未设置标准值");
        }
        if (LastT0Time == 0 && LastI1Current > 0.5 && LastI3Current == 0) {
            dlq.setLastt0time(dlqtest.getLastt0time());
            dlq.setLastt1time(dlqtest.getLastt1time());
            dlq.setLastt2time(dlqtest.getLastt2time());
            dlq.setLastt3time(dlqtest.getLastt3time());
            dlq.setLastt4time(dlqtest.getLastt4time());
            dlq.setLastt5time(dlqtest.getLastt5time());
            dlq.setLasti0current(dlqtest.getLasti0current());
            dlq.setLasti1current(dlqtest.getLasti1current());
            dlq.setLasti2current(dlqtest.getLasti2current());
            dlq.setLasti3current(dlqtest.getLasti3current());
            dlq.setLasti4current(dlqtest.getLasti4current());
            dlq.setLasti5current(dlqtest.getLasti5current());
            dlq.setLastdatatime(new Date());
        } else {
            dlq.setLastt0time(LastT0Time);
            dlq.setLastt1time(LastT1Time);
            dlq.setLastt2time(LastT2Time);
            dlq.setLastt3time(LastT3Time);
            dlq.setLastt4time(LastT4Time);
            dlq.setLastt5time(LastT5Time);
            dlq.setLasti0current(LastI0Current);
            dlq.setLasti1current(LastI1Current);
            dlq.setLasti2current(LastI2Current);
            dlq.setLasti3current(LastI3Current);
            dlq.setLasti4current(LastI4Current);
            dlq.setLasti5current(LastI5Current);
            dlq.setLastdatatime(new Date());
        }

        switch (cmd) {
            case 64:
                dlq.setAcount(dlq.getAcount() == null ? 0 : dlq.getAcount() + 1);
                break;
            case 65:
                dlq.setBcount(dlq.getBcount() == null ? 0 : dlq.getBcount() + 1);
                break;
            case 66:
                dlq.setCcount(dlq.getCcount() == null ? 0 : dlq.getCcount() + 1);
                break;
        }
        dlq.setLastcommunicationstatus(0);
        if (LastState == 1) {
            dlq.setLastaacurrent(temp.getLastaacurrent());
            dlq.setLastbacurrent(temp.getLastbacurrent());
            dlq.setLastcacurrent(temp.getLastcacurrent());
        } else if (LastState == 2) {
            dlq.setLastaccurrent(temp.getLastaccurrent());
            dlq.setLastbccurrent(temp.getLastbccurrent());
            dlq.setLastcccurrent(temp.getLastcccurrent());
        }
        dlq.setLastaastatus(temp.getLastaastatus());
        dlq.setLastbastatus(temp.getLastbastatus());
        dlq.setLastcastatus(temp.getLastcastatus());
        String alarmMessage = "";
        String alarmprefix = "";
        int alarmLevel = 0;
        if (dlq.getT2t2d() == null || dlq.getT3t3d() == null || dlq.getT4t4d() == null || dlq.getI2i2d() == null
                || dlq.getT5t5d() == null || dlq.getT1t0t1dt0d() == null || dlq.getT2t1t2dt1d() == null) {
            setText("未设置告警变量！请于告警设置界面设置！");
            return;
        }
        if (dlq.getLaststate() != 3 && dlq.getLaststate() != 4) {
            if (dlq.getLastt2time() > dlqtest.getLastt2time() + dlq.getT2t2d()
                    && dlq.getLastt3time() > dlqtest.getLastt3time() + dlq.getT3t3d()
                    && dlq.getLastt4time() > dlqtest.getLastt4time() + dlq.getT4t4d()
                    && dlq.getLasti2current() > dlqtest.getLasti2current() + dlq.getI2i2d()) {
                alarmMessage = alarmMessage + alarmprefix + stralarm[0];
                alarmLevel = 1;
                GetNormalWarn("断路器" + dlq.getDeviceaddr() + statusdisplay[dlq.getLaststate()] + "卡涩",
                        dlq.getDeviceaddr(), 0, dlq.getPointname(), alarmprefix + stralarm[0], true);
            } else {
                GetNormalWarn("断路器" + dlq.getDeviceaddr() + statusdisplay[dlq.getLaststate()] + "卡涩",
                        dlq.getDeviceaddr(), 0, dlq.getPointname(), "", false);
            }
            if (dlq.getLasti5current() > dlqtest.getLasti5current() && dlq.getLastt5time() > 99) {
                alarmMessage = alarmMessage + alarmprefix + stralarm[1];
                alarmLevel = 1;
                GetNormalWarn("断路器" + dlq.getDeviceaddr() + statusdisplay[dlq.getLaststate()] + "卡滞",
                        dlq.getDeviceaddr(), 0, dlq.getPointname(), alarmprefix + stralarm[1], true);
            } else {
                GetNormalWarn("断路器" + dlq.getDeviceaddr() + statusdisplay[dlq.getLaststate()] + "卡滞",
                        dlq.getDeviceaddr(), 0, dlq.getPointname(), "", false);
            }
            if ((Math.abs(dlq.getLastt5time() - dlqtest.getLastt5time()) < dlq.getT5t5d()
                    && dlq.getLasti3current() < dlqtest.getLasti3current() - 1)
                    || (Math.abs(dlq.getLastt5time() - dlqtest.getLastt5time()) > dlq.getT5t5d()
                            && dlq.getLasti3current() > dlqtest.getLasti3current() + 1)) {
                alarmMessage = alarmMessage + alarmprefix + stralarm[2];
                alarmLevel = 1;
                GetNormalWarn("断路器" + dlq.getDeviceaddr() + statusdisplay[dlq.getLaststate()] + "偏离",
                        dlq.getDeviceaddr(), 0, dlq.getPointname(), alarmprefix + stralarm[2], true);
            } else {
                GetNormalWarn("断路器" + dlq.getDeviceaddr() + statusdisplay[dlq.getLaststate()] + "偏离",
                        dlq.getDeviceaddr(), 0, dlq.getPointname(), "", false);
            }
            if ((Math.abs(dlqtest.getLastt1time() - dlqtest.getLastt0time()) > Math
                    .abs(dlq.getLastt1time() - dlq.getLastt0time()) + dlq.getT1t0t1dt0d())
                    && Math.abs(dlqtest.getLastt2time() - dlqtest.getLastt1time()) > (Math
                            .abs(dlq.getLastt2time() - dlq.getLastt1time()) + dlq.getT2t1t2dt1d())) {
                alarmMessage = alarmMessage + alarmprefix + stralarm[3];
                alarmLevel = 1;
                GetNormalWarn("断路器" + dlq.getDeviceaddr() + statusdisplay[dlq.getLaststate()] + "总行程",
                        dlq.getDeviceaddr(), 0, dlq.getPointname(), alarmprefix + stralarm[3], true);
            } else {
                GetNormalWarn("断路器" + dlq.getDeviceaddr() + statusdisplay[dlq.getLaststate()] + "总行程",
                        dlq.getDeviceaddr(), 0, dlq.getPointname(), "", false);
            }
        }

        dlq.setLifetime(dlq.getLifetime() - 100f / dlq.getMaxlifeconfig());
        dlq.setLastalarmlevel(alarmLevel);
        dlq.setLastalarmmessage(alarmMessage);
        dlq.setLastdatatime(new Date());
        example = new Example(Dlqjcsensor.class);
        criteria = example.createCriteria();
        criteria.andEqualTo("stationid", dlq.getStationid());
        criteria.andEqualTo("deviceaddr", dlq.getDeviceaddr());
        criteria.andEqualTo("devicegroup", dlq.getDevicegroup());
        criteria.andEqualTo("cmd", dlq.getCmd());
        criteria.andEqualTo("laststate", dlq.getLaststate());
        if (dlqserviceimpl.updateByExampleSelective(dlq, example) == 0) {
            setText("数据更新失败！请检查原因...");
        } else {
            setText("地址" + addrint + "：" + strdisplay[dlq.getCmd() - 64] + statusdisplay[dlq.getLaststate()]);
        }

        updateABCCount(addrint);
        addhis(dlq);
        addtest(dlq);
    }

    private void addtest(Dlqjcsensor dlq) {
        DlqjchistoryTest his = new DlqjchistoryTest();
        his.setStationid(dlq.getStationid());
        his.setDeviceaddr(dlq.getDeviceaddr());
        his.setDevicegroup(dlq.getDevicegroup());
        his.setPointname(dlq.getPointname());
        his.setDatatime(dlq.getLastdatatime());
        his.setT0time(dlq.getLastt0time() / 3);
        his.setT1time(dlq.getLastt1time() / 3);
        his.setT2time(dlq.getLastt2time() / 3);
        his.setT3time(dlq.getLastt3time() / 3);
        his.setT4time(dlq.getLastt4time() / 3);
        his.setT5time(dlq.getLastt5time() / 3);
        his.setI0current(dlq.getLasti0current());
        his.setI1current(dlq.getLasti1current());
        his.setI2current(dlq.getLasti2current());
        his.setI3current(dlq.getLasti3current());
        his.setI4current(dlq.getLasti4current());
        his.setI5current(dlq.getLasti5current());
        his.setCmd(dlq.getCmd());
        his.setLaststate(dlq.getLaststate());
        his.setStoragestate(dlq.getLaststoragestate());
        his.setAccurrent(dlq.getLastaccurrent());
        his.setBccurrent(dlq.getLastbccurrent());
        his.setCccurrent(dlq.getLastcccurrent());
        his.setAlarmlevel(dlq.getLastalarmlevel());
        his.setAlarmmessage(dlq.getLastalarmmessage());
        his.setCommunicationstatus(dlq.getLastcommunicationstatus());
        his.setInuse(dlq.getInuse());
        his.setLastbstate(dlq.getLastbstate());
        his.setLastcstate(dlq.getLastcstate());
        his.setLastbstoragestate(dlq.getLastbstoragestate());
        his.setLastcstoragestate(dlq.getLastcstoragestate());
        his.setAcount(dlq.getAcount());
        his.setBcount(dlq.getBcount());
        his.setCcount(dlq.getCcount());
        his.setLifetime(dlq.getLifetime());
        if (dlqjchistorytestmapper.insertSelective(his) == 0) {
            setText("行程历史动作表插入失败！请检查原因...");
        }
    }

    void addhis(Dlqjcsensor dlq) {
        List<Dlqjcsensor> dlqlist = dlqserviceimpl.getList(dlq).getData();
        Dlqjchistory his = new Dlqjchistory();
        for (int i = 0; i < dlqlist.size(); i++) {
            dlq = dlqlist.get(i);
            his.setStationid(dlq.getStationid());
            his.setDeviceaddr(dlq.getDeviceaddr());
            his.setDevicegroup(dlq.getDevicegroup());
            his.setPointname(dlq.getPointname());
            his.setDatatime(dlq.getLastdatatime());
            his.setT0time(dlq.getLastt0time());
            his.setT1time(dlq.getLastt1time());
            his.setT2time(dlq.getLastt2time());
            his.setT3time(dlq.getLastt3time());
            his.setT4time(dlq.getLastt4time());
            his.setT5time(dlq.getLastt5time());
            his.setI0current(dlq.getLasti0current());
            his.setI1current(dlq.getLasti1current());
            his.setI2current(dlq.getLasti2current());
            his.setI3current(dlq.getLasti3current());
            his.setI4current(dlq.getLasti4current());
            his.setI5current(dlq.getLasti5current());
            his.setCmd(dlq.getCmd());
            his.setLaststate(dlq.getLaststate());
            his.setStoragestate(dlq.getLaststoragestate());
            his.setAccurrent(dlq.getLastaccurrent());
            his.setBccurrent(dlq.getLastbccurrent());
            his.setCccurrent(dlq.getLastcccurrent());
            his.setAlarmlevel(dlq.getLastalarmlevel());
            his.setAlarmmessage(dlq.getLastalarmmessage());
            his.setCommunicationstatus(dlq.getLastcommunicationstatus());
            his.setInuse(dlq.getInuse());
            his.setLastbstate(dlq.getLastbstate());
            his.setLastcstate(dlq.getLastcstate());
            his.setLastbstoragestate(dlq.getLastbstoragestate());
            his.setLastcstoragestate(dlq.getLastcstoragestate());
            his.setAcount(dlq.getAcount());
            his.setBcount(dlq.getBcount());
            his.setCcount(dlq.getCcount());
            his.setLifetime(dlq.getLifetime());
            if (dlqserviceimpl.Add(his) == 0) {
                setText("历史表插入失败！请检查原因...");
            }
        }
    }

    @Async("threadPool")
    public void startSendThread(Appdevice Appdevice) throws Exception {
        int triprepeat = 5;
        if (ad.getSubswitch().equals("1")) {// 开启行程
            tripopen = true;
        } else {
            tripopen = false;
        }
        issend.put(Thread.currentThread().getId(), true);
        String cstr = "";
        String cmd[] = new String[3];
        cmd[0] = "7E%s804000000305";// 电流
        cmd[1] = "7E%s804100000305";// 行程
        checkType = "";

        timersp = (int) Math.round(Appdevice.getTimeoutsp() * 1000);
        while (issend.get(Thread.currentThread().getId()) != null) {
            synchronized (lock) {
                if (isrun) {
                    if ((addrindex + 6010) > Appdevice.getAddrmax() || (addrindex + 6010) < Appdevice.getAddrmin()) {
                        if (tripopen) {
                            if (currcmd == 0) {
                                currcmd = 1;
                            } else {
                                currcmd = 0;
                            }
                        }
                        addrindex = Appdevice.getAddrmin() - 6010;
                    }
                    if (currcmd == 1 && tripopen) {
                        if (!isfenhe[addrindex + 6010]) {
                            if (triprepeat > 0) {
                                triprepeat--;
                            } else {
                                triprepeat = 5;
                                addrindex++;
                                continue;
                            }
                        }
                        tripcount[addrindex + 6010]++;
                        if (tripcount[addrindex + 6010] > 3) {
                            tripcount[addrindex + 6010] = 0;
                            isfenhe[addrindex + 6010] = false;
                            addrindex++;
                            continue;
                        }
                    }
                    cstr = String.format(cmd[currcmd], String.format("%02X", addrindex));
                    Send(cstr);
                    if (reSend[addrindex] > 3) {
                        dlqserviceimpl.UpdateStatus(ad, addrindex + 6010, 1);
                        reSend[addrindex] = 0;
                        addrindex++;
                    }
                    reSend[addrindex]++;
                } else if (rescode != 0) {
                    setText(resmsg[rescode]);
                }
                lock.wait(timersp);
            }
        }
    }

    private void updateABCCount(Integer addr) {
        Dlqjcsensor dlq = new Dlqjcsensor();
        dlq.setStationid(ad.getStationid());
        dlq.setDevicegroup(ad.getDevicegroup());
        dlq.setDeviceaddr(addr);
        dlq.setCmd(67);

        Example example1 = new Example(Dlqjcsensor.class);
        Example.Criteria criteria1 = example1.createCriteria();
        criteria1.andEqualTo("stationid", ad.getStationid());
        criteria1.andEqualTo("deviceaddr", addr);
        criteria1.andEqualTo("devicegroup", ad.getDevicegroup());
        List<Dlqjcsensor> dlq1list = dlqserviceimpl.selectByExample(example1);
        long acount = 0, bcount = 0, ccount = 0;
        float lifetime = 0;
        int acountnum = 0, bcountnum = 0, ccountnum = 0, lifetimenum = 0;
        for (int i = 1; i < dlq1list.size(); i++) {
            if (dlq1list.get(i).getLaststate() == 3 || dlq1list.get(i).getLaststate() == 4)
                continue;
            if (dlq1list.get(i).getLifetime() != null && dlq1list.get(i).getLifetime() != 100) {
                lifetime += dlq1list.get(i).getLifetime();
                lifetimenum++;
            }
            if (dlq1list.get(i).getAcount() != null && dlq1list.get(i).getAcount() != 0) {
                acount += dlq1list.get(i).getAcount();
                acountnum++;
            }
            if (dlq1list.get(i).getBcount() != null && dlq1list.get(i).getBcount() != 0) {
                bcount += dlq1list.get(i).getBcount();
                bcountnum++;
            }
            if (dlq1list.get(i).getCcount() != null && dlq1list.get(i).getCcount() != 0) {
                ccount += dlq1list.get(i).getCcount();
                ccountnum++;
            }
        }
        dlq = dlq1list.get(0);
        if (lifetimenum > 0) {
            dlq.setLifetime(lifetime - lifetimenum * 100f + 100);
        }
        if (acountnum > 0) {
            dlq.setAcount(acount);
        }
        if (bcountnum > 0) {
            dlq.setBcount(bcount);
        }
        if (ccountnum > 0) {
            dlq.setCcount(ccount);
        }
        if (dlqserviceimpl.updateByPrimaryKeySelective(dlq) == 0) {
            setText("数据更新失败！请检查原因...");
        }
    }
}
